﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using VaccinationHost.Services;

namespace VaccinationHost.Controllers
{
    public class MyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        private UserService _userService;

        public MyAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, UserService userService) : base(options, logger, encoder, clock)
        {
            _userService = userService;
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            string openId = Request.Headers["OpenId"];
            //_userService.OpenId = openId;
          
            var currentUser = await _userService.CurrentUserAsync(openId);

            if (currentUser == null)
            {
                return AuthenticateResult.Fail("未登录");
            }
            else
            {
                var claims = new List<Claim>()
                {
                    new Claim(type:System.Security.Claims.ClaimTypes.Name, currentUser.Id)
                };

                var claimPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Api"));
                return AuthenticateResult.Success(new AuthenticationTicket(claimPrincipal, openId));
            }
        }
    }
    public static class MyAuthenticationSchemes
    {
        public const string CustomScheme = "CustomScheme";
    }
}
